package com.dengyin2000.javaeye.ordering.action;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Observer;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.datamodel.DataModelSelection;
import org.jboss.seam.core.Events;
import org.jboss.seam.faces.FacesMessages;

import com.dengyin2000.javaeye.ordering.entity.Dish;
import com.dengyin2000.javaeye.ordering.entity.DishOrder;
import com.dengyin2000.javaeye.ordering.entity.User;

@Name("orderListAction")
@Scope(ScopeType.SESSION)

public class OrderListAction implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 126414932859960654L;
	
	private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd");
	
	@In
	private User currentUser;
	
	@In(value="orderingDatabase")
	private Session session;
	
	@DataModel
	private List<DishOrder> dishOrders;
	
	@DataModelSelection
	private DishOrder order;
	
	@In
	private FacesMessages facesMessages;
	
	@In
	private Events events;
	
	@Factory("dishOrders")
	@Observer("orderConfirmed")
	@Transactional
	public void getDishOrders() { 
		Date now = new Date();
		Calendar instance = Calendar.getInstance();
		instance.setTime(now);
		instance.add(Calendar.DAY_OF_MONTH, 1);
		Date tomorrow = instance.getTime();
		Query query = session.createQuery("select distinct o from DishOrder o left join fetch o.dishes where o.user.id = :userId and o.createDate>=:startDate and o.createDate<:endDate order by o.createDate");
		query.setLong("userId", currentUser.getId());
		try {
			query.setDate("startDate", FORMAT.parse(FORMAT.format(now)));
			query.setDate("endDate", FORMAT.parse(FORMAT.format(tomorrow)));
		} catch (ParseException e) {
			query.setDate("startDate", now);
			query.setDate("endDate", tomorrow);
		}
		
		dishOrders =  query.list();
	}

	public DishOrder getOrder() {
		return order;
	}
	
	public List<Dish> getDishesList(DishOrder order){
		if (order.getDishes() == null)
			return null;
		List<Dish> rt = new ArrayList<Dish>();
		 rt.addAll(order.getDishes());
		return rt;
	}
	
	public void delOrder() {
		DishOrder order = (DishOrder) session.merge(getOrder()); 
		session.delete(order);
		facesMessages.add("成功退订！");
		events.raiseEvent("orderConfirmed");
	}
}
